package dev.ece.core.controller;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.lwjgl.glfw.GLFW;

/**
 * @author 潜行的青衣
 * @see
 */
public class Controller extends LinkedHashMap<Integer, Command> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5374827170890050397L;

	private boolean valid = true;
	
	private OtherKeyCommand otherKeyCommand;
	
	public void execute() {
		if(this.isValid()) {
			Iterator<Map.Entry<Integer, Command>> it = this.entrySet().iterator();
			while(it.hasNext()) {
				it.next().getValue().execute();
			}
		}
	}
	
	/**
	 * 
	 * @param window
	 * @param key
	 * @param scancode
	 * @param action
	 * @param mods
	 * @return 是否截获按键事件
	 */
	public boolean keyBoardEvent(int key, int action) {
		if(this.isValid()) {
			Command command = this.get(key);
			if(command != null) {
				if(GLFW.GLFW_PRESS == action) {
					command.setCanExecute(true);
					return true;
				} else if(GLFW.GLFW_RELEASE == action) {
					if(command.canExecute()) {
						command.setCanExecute(false);
					}
					return false;
				}
			} else {
				if(getOtherKeyCommand() != null) {
					if(GLFW.GLFW_PRESS == action) {
						getOtherKeyCommand().onKeyPress(key);
						return true;
					} else if(GLFW.GLFW_RELEASE == action) {
						getOtherKeyCommand().onKeyRelease(key);
						return false;
					}
				}
			}
		}
		return false;
	}

	public OtherKeyCommand getOtherKeyCommand() {
		return otherKeyCommand;
	}

	public void setOtherKeyCommand(OtherKeyCommand otherKeyCommand) {
		this.otherKeyCommand = otherKeyCommand;
	}

	public boolean isValid() {
		return valid;
	}

	public void setValid(boolean valid) {
		this.valid = valid;
		if(!valid) {
			this.stopCommands();
		}
	}
	/**
	 * 停止所有命令
	 */
	public void stopCommands() {
		Iterator<Command> it = this.values().iterator();
		while(it.hasNext()) {
			it.next().setCanExecute(false);
		}
		//停止
		if(getOtherKeyCommand() != null) {
			getOtherKeyCommand().onKeyRelease(0);
		}
	}
	
}
